package com.gxuwz.stats.controller.twoAdmin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxuwz.stats.config.CurrentLoginUserUtil;
import com.gxuwz.stats.entity.TotalWork;
import com.gxuwz.stats.security.jwt.JwtTokenUtil;
import com.gxuwz.stats.service.TotalWorkService;
import com.gxuwz.stats.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/twoAdminTotalWork")
public class TotalWorkTwoController {
    @Autowired
    private TotalWorkService totalWorkService;
    @Autowired
    private UserService userService;

    /**
     * 总工作量查询列表
     * @param currentPage
     * @param pageSize
     * @return
     */
    @GetMapping("/totalWorkList")
    public ResponseEntity<Map<String, Object>> totalWorkList(
            @RequestParam Map<String, String> params,
            @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestHeader("Authorization") String authorization) {
        try {
            // 提取 Token 并解析用户信息
            String token = authorization.replace("Bearer ", "");
            JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
//            int userId = jwtTokenUtil.getUserIdFromToken(token);
            String department = jwtTokenUtil.getDepartmentFromToken(token); // 获取部门信息
//            System.out.println("department="+department);

            // 创建 MyBatis Plus 的 Page 对象进行分页查询
            IPage<TotalWork> page = new Page<>(currentPage, pageSize);
            QueryWrapper<TotalWork> queryWrapper = new QueryWrapper<>();

            // 如果是二级学院管理员，添加 department 过滤条件
            if (department != null && !department.isEmpty()) {
                queryWrapper.eq("department", department); // 只查询当前部门的数据
            }

            // 模糊查询条件 - 用户姓名
            String consultingResultName = params.containsKey("userKeyword") && params.get("userKeyword") != null && !params.get("userKeyword").isEmpty() ? params.get("userKeyword") : null;
            // 调用 service 层的分页查询方法
            IPage<Map<String, Object>> resultPage = totalWorkService.getTotalWorkListWithUserInfo(page, department, consultingResultName);
//            System.out.println("用户总工作量的查询结果="+resultPage);

//            // 构造返回结果
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "查询成功");
            response.put("data", resultPage.getRecords()); // 当前页数据
            response.put("total", resultPage.getTotal()); // 总记录数
            System.out.println("总记录数="+resultPage.getTotal());
            response.put("currentPage", resultPage.getCurrent()); // 当前页码
            response.put("pageSize", resultPage.getSize()); // 每页大小
            response.put("totalPages", resultPage.getPages()); // 总页数

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    /**
     * 增加
     * @param totalWork
     * @return
     */
    @PostMapping("/addTotalWork")
    public ResponseEntity<Map<String, Object>> saveTotalWork(@RequestBody TotalWork totalWork) {
        System.out.println("前端数据：" + totalWork);

        // 创建响应 Map
        Map<String, Object> response = new HashMap<>();
        //1. 验证 username 是否存在
        String username = totalWork.getUsername();
        if (username == null || username.isEmpty()) {
            response.put("code", 400);
            response.put("msg", "用户名不能为空");
            return ResponseEntity.badRequest().body(response);
        }

        // 2. 根据 username 查询 user_id
        String userId = userService.getUserIdByUsername(username);
        if (userId == null) {
            response.put("code", 400);
            response.put("msg", "用户不存在");
            return ResponseEntity.badRequest().body(response);
        }
        System.out.println("获取到的 user_id：" + userId);

        // 3. 设置 user_id 并保存
        totalWork.setUserId(userId);
        try {
            // 保存到数据库
            totalWorkService.save(totalWork);

            // 返回成功响应
            response.put("code", 200);
            response.put("msg", "新增成功");
            return ResponseEntity.status(HttpStatus.CREATED).body(response);
        } catch (Exception e) {
            response.put("code", 500);
            response.put("msg", "服务器内部错误");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 修改
     */
    @PutMapping("/updateTotalWork")
    public ResponseEntity<Map<String, Object>> updateTotalWork(
            @RequestBody TotalWork totalWork
//            @RequestHeader("Authorization") String authorization
    ) {
        totalWorkService.updateById(totalWork);
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "修改成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 删除
     */
    @DeleteMapping("/deleteTwoTotalWork")
    public ResponseEntity<Map<String, Object>> deleteTwoTotalWork(@RequestBody List<Long> totalWorkIds) {
        System.out.println("删除：" + totalWorkIds);
        totalWorkService.removeByIds(totalWorkIds);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "删除成功");
        return ResponseEntity.ok(response);
    }

}
